#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

int pip_fd[2];
void display(char *);
int main(int argc, char *argv[]) {
  pipe(pip_fd);
  int fd = open("./file.txt", O_RDWR | O_CREAT | O_TRUNC, 0666);
  pipe(pip_fd);
  display(argv[1]);
  while (wait(NULL) != -1)
    ;
  char buf[1024];
  read(pip_fd[0], buf, 1024);
  write(fd, buf, strlen(buf));
  close(fd);
  return 0;
}

void display(char *path) {
  DIR *dir = opendir(path);
  if (dir == NULL) {
    perror("open fail");
    exit(-1);
  }

  struct dirent *di;
  char path_buf[1024];
  struct stat stat_buf;
  char buf[1024];
  char mod_buf[2024];
  while ((di = readdir(dir))) {
    bzero(buf, 1024);
    bzero(path_buf, 1024);
    if (!strcmp(".", di->d_name) || !strcmp("..", di->d_name))
      continue;
    snprintf(path_buf, 1024, "%s/%s", path, di->d_name);
    stat(path_buf, &stat_buf);
    if (S_ISDIR(stat_buf.st_mode)) {
      // dir name
      // write(pip_fd[1],di->d_name,strlen(di->d_name));
      pid_t pid;
      pid = fork();
      if (pid == 0) {
        display(path_buf);
        exit(0);
      }
    } else {
      bzero(mod_buf, sizeof(mod_buf));
      snprintf(mod_buf, 1025, "%s\n", path_buf);
      write(pip_fd[1], mod_buf, strlen(mod_buf));
    }
  }
}
